<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="9">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="userName" label="用户名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="phoneNo" label="手机号"></el-table-column>
        <el-table-column prop="groupName" label="角色">
          <template slot-scope="scope">
            <span v-if="scope.row.groupName == 0">高管</span>
            <span v-if="scope.row.groupName == 1">普通用户</span>
            <span v-if="scope.row.groupName == 2">高管</span>
            <span v-if="scope.row.groupName == 3">职工</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column> -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteManger(scope.row.userName)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                @click="showRoleDailog(scope.row)"
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页按钮 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="addUserInfo"
    >
      <el-form
        ref="AddUserFormRef"
        :model="addUser"
        :rules="AddUserFormRules"
        label-width="70px"
      >
        <el-form-item prop="userName" label="用户名">
          <el-input v-model="addUser.userName"></el-input>
        </el-form-item>
        <el-form-item prop="passWord" label="密码">
          <el-input v-model="addUser.passWord" type="password"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="addUser.email"></el-input>
        </el-form-item>
        <el-form-item prop="phoneNo" label="手机号">
          <el-input v-model="addUser.phoneNo"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsers">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="editUserInfo"
    >
      <el-form
        ref="editUserFormRef"
        :model="editUser"
        :rules="editUserFormRules"
        label-width="70px"
      >
        <el-form-item prop="userName" label="用户名">
          <el-input v-model="editUser.userName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="editUser.email"></el-input>
        </el-form-item>
        <el-form-item prop="phoneNo" label="手机号">
          <el-input v-model="editUser.phoneNo"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUsers">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="SettingRoleDialogVisible"
      width="50%"
    >
      <div>
        <p>姓名：{{ userInfo.userName }}</p>
        <p>
          角色：{{
            userInfo.groupName == 0
              ? "高管"
              : userInfo.groupName == 1
              ? "普通用户"
              : userInfo.groupName == 2
              ? "高管"
              : "职工"
          }}
        </p>
        <div>
          <span>分配角色:</span>
          &nbsp;&nbsp;
          <el-select v-model="selectedRole" placeholder="请选择">
            <el-option
              v-for="item in rolelist"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="SettingRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="SettingRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { async } from "q";
import { userInfo } from "os";
export default {
  data() {
    // 验证邮箱规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/;
      if (regEmail.test(value)) {
        return cb();
      }
      //返回一个错误提示
      cb(new Error("请输入合法的邮箱"));
    };
    // 验证手机号
    var checkphoneNo = (rule, value, cb) => {
      const regphoneNo = /^1[34578]\d{9}$/;
      if (regphoneNo.test(value)) {
        return cb();
      }
      //返回一个错误提示
      cb(new Error("请输入合法的手机号"));
    };
    return {
      queryInfo: {
        query: "",
        // 当前的页码
        pagenum: 1,
        // 当前每页展示多少条数据
        pagesize: 10,
      },
      userList: [],
      total: 0,
      // 添加用户对话框默认为关闭
      dialogVisible: false,
      // 修改用户对话框默认为关闭
      editdialogVisible: false,
      //添加用户数据
      addUser: {
        userName: "",
        passWord: "",
        email: "",
        phoneNo: "",
      },
      //修改用户数据
      editUser: {
        userName: "",
        passWord: "",
        email: "",
        phoneNo: "",
      },
      //分配角色弹出框默认为false
      SettingRoleDialogVisible: false,
      //修改用户的验证规则
      editUserFormRules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 5, max: 10, msg: "长度在3到10个字符", trigger: "blur" },
        ],
        passWord: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 5, max: 10, msg: "长度在3到10个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: checkEmail,
            message: "邮箱格式不正确,请重新输入",
            trigger: "blur",
          },
        ],
        phoneNo: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: checkphoneNo,
            message: "手机号格式不正确,请重新输入",
            trigger: "blur",
          },
        ],
      },
      //添加用户的验证规则
      AddUserFormRules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 5, max: 10, msg: "长度在5到10个字符", trigger: "blur" },
        ],
        passWord: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 5, max: 10, msg: "长度在5到10个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: checkEmail,
            message: "邮箱格式不正确,请重新输入",
            trigger: "blur",
          },
        ],
        phoneNo: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: checkphoneNo,
            message: "手机号格式不正确,请重新输入",
            trigger: "blur",
          },
        ],
      },
      userInfo: {},
      // 分配角色列表
      rolelist: [
        // {
        //   roleName: "高管",
        //   id: 0,
        // },
        {
          roleName: "普通用户",
          id: 1,
        },
        {
          roleName: "高管",
          id: 2,
        },
        {
          roleName: "职工",
          id: 3,
        },
      ],
      // 选择框
      selectedRole: "",
    };
  },
  //data初始化完成 el未初始化
  created() {
    //调用函数获取数据
    this.getUserList();
  },
  methods: {
    //异步
    async getUserList() {
      const { data: res } = await this.$http.post("/user/getAllUser", {
        query: this.queryInfo.query,
        pagenum: this.queryInfo.pagenum,
        pagesize: this.queryInfo.pagesize,
      });
      console.log(res);
      if (res.code != 200) {
        return this.$message.error("获取用户列表失败!");
      }
      this.userList = res.data.users;
      this.total = res.data.count;
    },
    // /user/getUser/{userName}
    // async userStateChanged(userinfo) {
    //   const { data: res } = await this.$http.put(
    //     `users/${userinfo.id}/state/${userinfo.mg_state}`
    //   );
    //   if (res.meta.status != 200) {
    //     userinfo.mg_state = !userinfo.mg_state;
    //     return this.$Message.error("更新状态失败!");
    //   }
    //   this.$Message.success("更新状态成功!");
    // },
    // 监听newSize改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 显示页码值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    // 关闭form表单之后重置内容
    // 首先为表单注册一个close事件，事件名为addUserInfo，然后通过$refs.AddUserFormRef.resetFileds()清空表单数据
    addUserInfo() {
      this.$refs.AddUserFormRef.resetFields();
    },

    //在修改的时候 关闭form表单之后重置内容
    editUserInfo() {
      this.$refs.editUserFormRef.resetFields();
    },

    //点击确定按钮添加用户
    addUsers() {
      // 预校验查看输入是否正确，如果正确的话输出log valid为true
      this.$refs.AddUserFormRef.validate(async (valid) => {
        //如果valid不为true返回
        if (!valid) return;
        // 解构赋值 使用post请求发送数据
        const { data: res } = await this.$http.post("registered", this.addUser);
        //如果status不为201的话添加失败 this.$Message.error
        if (res.code != 200) {
          return this.$message.error("添加用户失败!");
        }
        //添加成功的话$Messgae.success("添加成功")
        this.$message.success("添加用户成功!");
        // 隐藏添加用户的对话框
        this.dialogVisible = false;
        // 重新获取数据列表
        this.getUserList();
      });
    },
    // 修改用户
    editUsers() {
      // 预校验查看输入是否正确，如果正确的话输出log valid为true
      this.$refs.editUserFormRef.validate(async (valid) => {
        //如果valid不为true返回
        if (!valid) return;
        // 解构赋值 使用post请求发送数据
        const { data: res } = await this.$http.post("users/update", {
          email: this.editUser.email,
          phoneNo: this.editUser.phoneNo,
        });
        // //如果status不为201的话添加失败 this.$Message.error

        if (res.meta.status != 200) {
          return this.$Message.error("修改用户失败!");
        }
        // 隐藏添加用户的对话框
        this.editdialogVisible = false;
        // 重新获取数据列表
        this.getUserList();
        //添加成功的话$Messgae.success("添加成功")
        this.$Message.success("修改用户成功!");
      });
      this.$http
        .put(`users/${this.editUser.id}`, {
          email: this.editUser.email,
          phoneNo: this.editUser.phoneNo,
        })
        .then((res) => {
          if (res.data.meta.status != 200) {
            return this.$message.error("修改失败");
          }
          this.editdialogVisible = false;
          this.getUserList();
          this.$Message.success("修改用户成功!");
        });
    },
    showEditDialog(userinfo) {
      this.editdialogVisible = true;
      // this.editUser.id = userinfo.id;
      this.editUser.userName = userinfo.userName;
      this.editUser.email = userinfo.email;
      this.editUser.phoneNo = userinfo.phoneNo;
    },
    // 根据ID删除信息
    async deleteManger(userName) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件,是否继续",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult == "cancel") {
        return this.$Message.info("取消了删除");
      }
      // 点击确定发送请求
      const { data: res } = await this.$http.delete("user/delUser/" + userName);
      if (res.code != 200) {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      this.getUserList();
    },
    // 展示分配角色弹窗
    async showRoleDailog(userinfo) {
      this.userInfo = userinfo;
      this.SettingRoleDialogVisible = true;
      // const { data: res } = await this.$http.get("/user/update");
      // if (res.meta.status != 200) {
      //   return false;
      // }
      // this.rolelist = res.data;
    },
    //分配用户角色
    async SettingRole() {
      const { data: res } = await this.$http.post("/user/update", {
        groupName: this.selectedRole,
        userName: this.userInfo.userName,
      });
      // const { data: res } = await this.$http.put(
      //   `users/${this.userInfo.id}/role`,
      //   {
      //     rid: this.selectedRole,
      //   }
      // );
      if (res.code != 200) {
        return this.$Message.error("修改角色失败");
      }
      this.$message.success("成功");
      this.SettingRoleDialogVisible = false;
      this.getUserList();
    },
  },
};
</script>
<style lang="less">
.el-breadcrumb {
  margin-bottom: 15px;
  font-size: 12px;
}
.el-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
}
.el-row {
  margin-bottom: 10px;
}
.el-pagination {
  margin-top: 15px;
}
</style>